package com.lzy.utils;

import javax.servlet.http.HttpServletRequest;

public class IPUtl {

    /**
     * 获取ip地址(代理ip)
     *
     * @return ipAddr
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("PRoxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 拼装ip显示的格式  192.*.*.155
     *
     * @param ip
     * @return
     */
    public static String getIp(String ip) {
        String ipShowStr = ip.substring(ip.indexOf("."), ip.lastIndexOf(".")); //获取要显示*的位置
        String ipNumReStr = ipShowStr.replaceAll("[0-9]", "*");//使用表达式替换  数字替换*
        String[] ipStrs = ipNumReStr.replace(".", ",").split(",");
        StringBuffer sb = new StringBuffer();
        for (String s : ipStrs) {
            if (s != null && !s.equals("")) {
                sb.append(s.trim().replace(s, ".*")); //将多个*，替换成一个*
            }

        }
        String ipFirst = ip.substring(0, ip.indexOf("."));// 第一个ip
        String ipLast = ip.substring(ip.lastIndexOf(".") + 1, ip.length()); // 最后一个ip
        //拼装ip
        String ipFin = ipFirst + sb.toString() + "." + ipLast;
        return ipFin;
    }
}
